<?php

# http://projects:8081/cdapp-2kt-api/api/seat_status_history.php

include_once '_portal.php';

$action = $_GET['action'];

if ($action == 'queryHistory') {
  query_history($post);
} elseif ($action == 'dedup') {
  dedup($_GET['start']);
}

die();

function query_history($post) {
  $begin = isset($post->begin) ? $post->begin : strtotime('yesterday');
  $end = isset($post->end) ? $post->end : time();

  $sql = "SELECT * FROM `2kt_seat_status_history` WHERE `moment`>= '{$begin}' AND `moment` <= '{$end}' ORDER BY `moment` ASC";

  $result = exec_sql($sql);

  if ($result) {
    output(['params' => ['begin' =>$begin, 'end' => $end], 'sql' => $sql, 'result' => query_parse($result)]);
  } else {
    output(['params' => ['begin' => date('Y-m-d H:i:s', $begin), 'end' => date('Y-m-d H:i:s', $end)], 'sql' => $sql, 'result' => []]);
  }
}

function dedup($start = 0) {
  $list = [];
  $end = $start + 1000;
  $sql = "SELECT * FROM `2kt_seat_status_history` ORDER BY `moment` ASC LIMIT {$start} , 10000";
  echo $sql . PHP_EOL . PHP_EOL;
  $result = exec_sql($sql);
  if (!$result) {
    die('Wrong');
  }
  $first = 0;
  for ($i = 0; $i < count($result); $i++) {
    if ($i > 0) {
      if ($result[$i]['status'] == $result[$i - 1]['status']) {
        if ($result[$i]['counting'] == $result[$i - 1]['counting']) {
          if ($result[$i]['direction'] == $result[$i - 1]['direction']) {
            $list[] = $result[$i]['moment'];
            if ($first == 0) {
              $first = $i;
            }
          }
        }
      }
    }
  }
  $list_str = implode("','", $list);
  $sql = "DELETE FROM `2kt_seat_status_history` WHERE `moment` IN ('{$list_str}')";
  echo exec_sql($sql) . ' :: ' . ($start + $first) . PHP_EOL;
  echo $sql . PHP_EOL . PHP_EOL;
}